/*
* Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

use std::ffi::c_void;

use crate::mw_server::{MWServer, MWServerKind};

#[unsafe(no_mangle)]
pub unsafe extern "C" fn ohmw_mw_server_create(kind: MWServerKind) -> *mut c_void {
    let server = match MWServer::new(kind) {
        Ok(server) => server,
        Err(err) => {
            tracing::error!("{err:?}");
            return std::ptr::null_mut();
        },
    };
    Box::into_raw(Box::new(server)) as *mut c_void
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn ohmw_mw_server_destroy(server: *mut c_void) {
    let server: Box<MWServer> = unsafe { Box::from_raw(server.cast()) };
    let MWServer { .. } = *server;
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn ohmw_mw_server_start(server: *mut c_void) -> i32 {
    let server: &mut MWServer = Box::leak(unsafe { Box::from_raw(server.cast()) });
    match server.start() {
        Ok(_) => 0,
        Err(err) => {
            tracing::error!("{err:?}");
            -1
        },
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn ohmw_mw_server_stop(server: *mut c_void) -> i32 {
    let server: &mut MWServer = Box::leak(unsafe { Box::from_raw(server.cast()) });
    match server.stop() {
        Ok(_) => 0,
        Err(err) => {
            tracing::error!("{err:?}");
            -1
        },
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn ohmw_mw_server_is_running(kind: MWServerKind) -> bool {
    MWServer::is_running(kind)
}
